<template>
  <div>
    <el-form ref="form" label-width="80px" :inline="false">
      <el-form-item label="SKU名称">
        <el-input placeholder="请你输入SKU的名称" v-model="addSkuParams.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input type="number" placeholder="请你输入SKU的价格" v-model="addSkuParams.price"></el-input>
      </el-form-item>
      <el-form-item label="重量(g)">
        <el-input type="number" placeholder="请你输入SKU的重量" v-model="addSkuParams.weight"></el-input>
      </el-form-item>
      <el-form-item label="SKU描述">
        <el-input type="textarea" placeholder="请你输入SKU的描述" v-model="addSkuParams.skuDesc"></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form label-width="80px" :inline="true">
          <el-row>
            <el-col :span="8" v-for="(attr) in spuattrlist" :key="attr.id">
              <el-form-item :label="attr.attrName">
                <el-select v-model="attr.attrValIdAndAttrValueId">
                  <el-option
                    :label="attrVal.valueName"
                    :value="attr.id+':'+attrVal.id"
                    v-for="(attrVal,index) in attr.attrValueList"
                    :key="attrVal.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form label-width="80px">
          <el-row>
            <el-col :span="8" v-for="saleAttr in spusaleattrlist" :key="saleAttr.id">
              <el-form-item :label="saleAttr.saleAttrName">
                <el-select
                  placeholder="请选择"
                  v-model="saleAttr.saleattrValIdAndsaleAttrValueId"
                  style="width:200px"
                >
                  <el-option
                    :label="saleAttrVal.saleAttrValueName"
                    :value="saleAttr.id+':'+saleAttrVal.id"
                    v-for="saleAttrVal in saleAttr.spuSaleAttrValueList"
                    :key="saleAttrVal.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-form-item>
      <el-form-item label="图片名称">
        <el-table border  :data="spuimagelist" ref="table" @select-all="selectAll" @select="select" >
          <el-table-column type="selection" ></el-table-column>
          <el-table-column label="图片" prop="imgUrl">
            <template #="{row}">
              <img :src="row.imgUrl" style="height:100px" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template #="{row}">
              <el-button type="primary" size="default" v-if="row.default==1">默认图片</el-button>
              <el-button type="warning" size="default" v-else @click="setDefault(row)">设置默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="save">保存</el-button>
    <el-button @click="cancel">取消</el-button>
  </div>
</template>

<script setup lang="ts">
import { nextTick, ref } from 'vue'
import {
  reqSpuAttrList,
  reqAttrInfoList,
  reqSpuImageList,
  reqSaveSkuInfo,
} from '@/api/product/spu/index'
import type { tAddAttrParam } from '@/api/product/spu/model/index'
import useCategoryStore from '@/stores/category'
import { add } from 'lodash'
import { ElMessage } from 'element-plus'
const cateStore = useCategoryStore()
const table = ref()
const addSkuParams = ref<any>({
  category3Id: 0,
  price: 0,
  weight: '',
  spuId: 0,
  tmId: 0,
  skuDefaultImg: '',
  skuDesc: '',
  skuName: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
})

const spuattrlist = ref<tAddAttrParam[]>([])
const spuimagelist = ref<any>([])
const spusaleattrlist = ref<any>([])
const $emit = defineEmits(['changeSene'])
let initSkuData = async (row: any) => {
  Object.assign(addSkuParams.value, {
    category3Id: 0,
    price: 0,
    weight: '',
    spuId: 0,
    tmId: 0,
    skuDefaultImg: '',
    skuDesc: '',
    skuName: '',
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
  })
 spuattrlist.value=[]
 spuimagelist.value=[]
 spusaleattrlist.value = []

  spuattrlist.value = await reqAttrInfoList(
    cateStore.state.c1Id,
    cateStore.state.c2Id,
    cateStore.state.c3Id
  )
  spuimagelist.value = await reqSpuImageList(row.id)
  spusaleattrlist.value = await reqSpuAttrList(row.id)
  addSkuParams.value.category3Id = row.category3Id
  addSkuParams.value.spuId = row.id
  addSkuParams.value.tmId = row.tmId
  spuimagelist.value.forEach((item: any, index: number) => {
    item.default = 0
  })
  spuimagelist.value[0].default = 1
  addSkuParams.value.skuDefaultImg = spuimagelist.value[0].imgUrl
  nextTick(() => {
    table.value.toggleRowSelection(spuimagelist.value[0], true)
  })
}
const setDefault = (row: any) => {
  spuimagelist.value.forEach((item: any) => {
    item.default = 0
    nextTick(() => {
      table.value.toggleRowSelection(item, false)
    })
  })
  row.default = 1
  addSkuParams.value.skuDefaultImg = row.imgUrl
  nextTick(() => {
    table.value.toggleRowSelection(row, true)
  })
}
const save = async () => {
  const skuAttrValueList = spuattrlist.value.reduce((pre: any[], cur: any) => {
    console.log(cur)
    if (cur.attrValIdAndAttrValueId) {
      pre.push({
        attrId: cur.attrValIdAndAttrValueId.split(':')[0],
        valueId: cur.attrValIdAndAttrValueId.split(':')[1],
      })
    }
    return pre
  }, [])
  const skuSaleAttrValueList = spusaleattrlist.value.reduce(
    (pre: any[], cur: any) => {
      if (cur.saleattrValIdAndsaleAttrValueId) {
        pre.push({
          saleAttrId: cur.saleattrValIdAndsaleAttrValueId.split(':')[0],
          saleAttrValueId: cur.saleattrValIdAndsaleAttrValueId.split(':')[1],
        })
      }

      return pre
    },
    []
  )
  addSkuParams.value.skuAttrValueList = skuAttrValueList
  addSkuParams.value.skuSaleAttrValueList = skuSaleAttrValueList
  try {
    await reqSaveSkuInfo(addSkuParams.value)
    ElMessage({
      type: 'success',
      message: '添加SKU成功！',
    })
    $emit('changeSene', 1)
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '添加SKU失败！',
    })
  }
}
const cancel = () => {
  $emit('changeSene', 1)
}
const select =(selection:any, row:any) =>{
   selection.forEach((item:any)=>{
         item.default= 0
         table.value.toggleRowSelection(item,false)
   })
   row.default=1
   addSkuParams.value.skuDefaultImg =  row.imgUrl
   table.value.toggleRowSelection(row,true)
}
const selectAll =(selection:any)=>{
     selection.forEach((item:any)=>{
        item.default =0
     })
     spuimagelist.value[0].default=1
     addSkuParams.value.skuDefaultImg =   spuimagelist.value[0].imgUrl
     nextTick(()=>{
        table.value.clearSelection()
        table.value.toggleRowSelection(spuimagelist.value[0],true)
    })
    return ElMessage({
        type:'warning',
        message:'只能选择一个不能多选！'
     })
}
defineExpose({ initSkuData })
</script>

<style scoped>
</style>